package com.blb.edufileservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.blb.edufileservice.feign.CourseFeign;
import com.blb.edufileservice.service.IPageService;
import com.learn.eduapi.entity.Course;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class PageServiceImpl implements IPageService {

    @Value("${page.path}")
    private String pagePath;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private CourseFeign courseFeign;

    @Override
    public Course createCoursePage(Integer courseId) {
        File dir = new File(pagePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        Map<String,Object> var = new HashMap<>();
        Course course = courseFeign.getCourseById(courseId);
        var.put("course", course);
        Context context = new Context();
        context.setVariables(var);
        String filename = pagePath + course.getId() + ".html";
        try(PrintWriter printWriter = new PrintWriter(filename)){
            templateEngine.process("course",context,printWriter);
            log.info("创建页面文件完成" + filename);
        }catch (IOException ex){
            log.error("创建页面文件出现异常",ex);
        }
        return course;
    }

    @Override
    public void deleteCoursePage(Integer courseId) {
        String filename = pagePath + courseId + ".html";
        File file = new File(filename);
        if(file.exists()){
            file.delete();
            log.info("删除页面文件完成"+filename);
        }else{
            log.info("页面文件不存在");
        }
    }
}
